<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm"
           :class="isEdit?'':'formItem'"
           :label-position="labelPosition">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="header-card">
        <span class="header-card-title">保养项目明细</span>
      </div>
      <el-row>
        <el-col :span="24" v-if="isShow" style="margin-bottom: 16px;">

          <div class="decoration-illustrate" v-if="isEdit">
            <span>保养合计费用：¥{{ format_thousand(addAmountNun) }}</span>
          </div>
          <el-table size="mini" :data="ruleForm.carMaintainProjectList" border style="width: 100%">
            <el-table-column align="center" label="操作" width="100" v-if="isEdit">
              <template #default="{row,$index}">
                <el-button size="mini" type="text" @click="delDecoration(row, $index )">删除</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" label="保养项目名称">
              <template #default="{row}">
                <el-input v-model="row.maintainName" v-if="isEdit" size="mini"></el-input>
                <span v-else>
                    {{ row.maintainName }}
                  </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="金额/元">
              <template #default="{row,$index}">
                <el-input v-model="row.price" v-if="isEdit" @change="changeTable(row,$index,'price')"
                          size="mini"></el-input>
                <span v-else>
                    {{ format_thousand(row.price) }}
                  </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="详细信息">
              <template #default="{row}">
                <el-input v-model="row.detailedInfo" v-if="row.disabled && isEdit" size="mini"></el-input>
                <span v-else>
                    {{ row.detailedInfo }}
                  </span>
              </template>
            </el-table-column>
            <template v-slot:append v-if="isEdit">
              <div class="flex-xy-center" style="height: 30px">
                <e-button type="text" icon="eel-icon-plus" @click="addDecoration">添加
                </e-button>
              </div>
            </template>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col v-if="isShow">
          <el-form-item label="上传附件:" prop="maintainProjectUrl">
            <ImageCommon v-model="ruleForm.maintainProjectUrl" :limit="20" :upType="2" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
      </el-row>

    </el-card>
  </el-form>
</template>

<script>

export default {
  name: 'maintenanceTtem',

  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    }
  },
  computed: {
    ruleForm: {
      get() {
        let that = this
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key)
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key)
            }
            that.$emit('input', {...target, [key]: value})
            return true
          }
        })
        return proxy
      }
    },
    labelPosition() {
      if (this.isEdit) {
        return "top";
      } else {
        return "left";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool
    },
  },
  watch: {
    'value.maintainType': {
      handler(val) {
        if (val) {
          this.handleCount(val)
        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    var validateMaintainProjectUrl = (rule, value, callback) => {
      if (this.ruleForm.maintainProjectUrl === "" || this.ruleForm.maintainProjectUrl === null) {

        callback(new Error("请上传图片"));
      } else {
        callback();
      }
    };
    return {
      isShow: true,
      addAmountNun: 0,
      rules: {
        maintainProjectUrl: [
          {
            required: this.state === "write",
            validator: validateMaintainProjectUrl,
            trigger: "blur",
          }
        ]
      }
    }
  },
  methods: {
    handleCount(val) {
      if (Number(val) === 1) {
        this.addAmountNun = 0;
      }
      if (Number(val) === 2) {
        let totalCents = 0;
        for (let i = 0; i < this.value.carMaintainProjectList.length; i++) {
          totalCents += Math.round(Number(this.value.carMaintainProjectList[i].price) * 100);
        }
        // Convert totalCents back to dollars
        this.addAmountNun = (totalCents / 100).toFixed(2);
      }
    },


    //新增保养项目明细
    addDecoration() {
      let obj = {
        maintainName: "",
        detailedInfo: "",
        price: "",
        disabled: true,
      }
      this.ruleForm.carMaintainProjectList.push(obj)
    },

    //删除保养项目明细
    delDecoration(row, key) {
      this.ruleForm.carMaintainProjectList.splice(key, 1)
      if (this.ruleForm.maintainType === '2') {
        this.addAmountNun = this.addAmount(this.ruleForm.carMaintainProjectList, 'price')
      } else {
        this.addAmountNun = 0
      }

    },

    changeTable(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/
      if (msg.test(Number(row[field]))) {
        if (Number(row[field]) >= 0) {
          let _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
          row[field] = _value
        } else {
          row[field] = ""
        }
      } else {
        row[field] = ""
      }
      if (this.ruleForm.maintainType === '2') {
        this.addAmountNun = this.addAmount(this.ruleForm.carMaintainProjectList, 'price')
      } else {
        this.addAmountNun = 0
      }

    },

    addAmount(arr, field) {
      let arrNum = JSON.parse(JSON.stringify(arr))
      let num = 0
      if (arrNum && arrNum.length > 0) {
        arrNum.forEach((v) => {
          if (!v[field]) {
            v[field] = 0
          }
          num += Math.round(Number(v[field]) * 100)
        })
      } else {
        num = 0
      }
      return (num / 100).toFixed(2)
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr();
            reject();
          }
        });
      });
    },
    locateToErr() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("is-error");
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth",
        });
      });
    },
    valid() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },
  }

};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";

.decoration-illustrate {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}


::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #464646;
}

</style>


